//
//  CustomerMasterTableViewController.m
//  CollectionManagerFlow
//
//  Created by Sophia Tsay on 4/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CustomerMasterTableViewController.h"
#import "AssignedCustomersViewController.h"
#import "BalanceDetailViewController.h"

@interface CustomerMasterTableViewController ()
@property (nonatomic, weak) UIPopoverController *popoverVC;
@property (nonatomic, weak) UIPopoverController *topPopoverVC;
@property (nonatomic, strong) IBOutlet UIBarButtonItem *customerButton;
@property (nonatomic, strong) UIViewController *balanceDetailViewController;
@property (nonatomic, strong) UIViewController *CEIViewController;
@property (nonatomic, strong) UIViewController *percentCurrentViewController;
@property (strong, nonatomic) IBOutlet UIImageView *collectorImageView;
@property (strong, nonatomic) UIViewController *dsoViewController;
@end

@implementation CustomerMasterTableViewController
@synthesize customerTableView = _customerTableView;
@synthesize customerHeaderView = _customerHeaderView;
@synthesize detailButton = _detailButton;
//@synthesize collectorName = _collectorName;
@synthesize toolBar = _toolBar;
@synthesize popoverVC = _popoverVC;
@synthesize objectName = _objectName;
@synthesize topPopoverVC = _topPopoverVC;
@synthesize customerButton = _customerButton;
@synthesize objectType = _objectType;
@synthesize balanceDetailViewController = _balanceDetailViewController;
@synthesize CEIViewController = _CEIViewController;
@synthesize percentCurrentViewController = _percentCurrentViewController;
@synthesize dsoViewController = _dsoViewController;

@synthesize collectorImageView = _collectorImageView;

#define DEFAULT_COLLECTOR_NAME @"Claudia Renner";
#define COLLECTOR_DEFAULT_NAME @"collector_default_name"
#define DEFAULT_CUSTOMER_NAME @"Microsoft";
#define CUSTOMER_DEFAULT_NAME @"customer_default_name"
/*
- (NSString *)collectorName
{
    if (!_collectorName) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *default_collectorName = [defaults objectForKey:COLLECTOR_DEFAULT_NAME];
        if (!default_collectorName) {
            return DEFAULT_COLLECTOR_NAME;
        } else {
            return default_collectorName;
        }
    } else {
        return _collectorName;
    }    
}

- (void) setCollectorName:(NSString *)collectorName
{
    if (collectorName != _collectorName) {
        _collectorName = collectorName;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:_collectorName forKey:COLLECTOR_DEFAULT_NAME];
        [defaults synchronize];
    }
}
*/

- (UIViewController *)balanceDetailViewController
{
    if (!_balanceDetailViewController) {
        //UIStoryboard *storyBoard = self.storyboard;
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
        _balanceDetailViewController = [storyBoard instantiateViewControllerWithIdentifier:@"BalanceDetailViewController"];        
    }
    return _balanceDetailViewController;
}

- (UIViewController *)CEIViewController
{
    if (!_CEIViewController) {
        //UIStoryboard *storyBoard = self.storyboard;
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
        _CEIViewController = [storyBoard instantiateViewControllerWithIdentifier:@"CEIViewController"];
    }
    return _CEIViewController;
}

- (UIViewController *)percentCurrentViewController
{
    if (!_percentCurrentViewController) {
        //UIStoryboard *storyBoard = self.storyboard;
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
        _percentCurrentViewController = [storyBoard instantiateViewControllerWithIdentifier:@"percentCurrentViewController"];
    }
    return _percentCurrentViewController;
}

-(UIViewController *)dsoViewController
{
    if(!_dsoViewController) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
        _dsoViewController = [storyBoard instantiateViewControllerWithIdentifier:@"DSO View Controller"];
    }
    return _dsoViewController;
}


- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {
    //If scaleFactor is not touched, no scaling will occur      
    CGFloat scaleFactor = 1.0;
    
    //Deciding which factor to use to scale the image (factor = targetSize / imageSize)
    if (image.size.width > targetSize.width || image.size.height > targetSize.height)
        if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
            scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
    
    UIGraphicsBeginImageContext(targetSize); 
    
    //Creating the rect where the scaled image is drawn in
    CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2,
                             (targetSize.height -  image.size.height * scaleFactor) / 2,
                             image.size.width * scaleFactor, image.size.height * scaleFactor);
    
    //Draw the image into the rect
    [image drawInRect:rect];
    
    //Saving the image, ending image context
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
}

- (void) setCustomerButton:(UIBarButtonItem *)customerButton
{
    [customerButton setTitle:self.objectName];
/*
    NSURL *imageURL = [NSURL URLWithString:@"http://www.toms-blog.com/images/Medium/microsoft-icon-new.jpg"];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    UIImage *newImage = [self scaleImage:image toSize:CGSizeMake(36, 36)];
    //customerButton.image = newImage;
    [customerButton setBackgroundImage:newImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
 */
    if (customerButton != _customerButton) {
        _customerButton = customerButton;
    }
}

- (NSString *)objectName
{
//    if (!_objectName) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([self.objectType isEqualToString:@"Customer"]) 
        {
            NSString *default_customerName = [defaults objectForKey:CUSTOMER_DEFAULT_NAME];
            if (!default_customerName) {
                _objectName = DEFAULT_CUSTOMER_NAME;
            } else {
                _objectName = default_customerName;
            }
        } else if ([self.objectType isEqualToString:@"Collector"])
        {
            NSString *default_collectorName = [defaults objectForKey:COLLECTOR_DEFAULT_NAME];
            if (!default_collectorName) {
                _objectName = DEFAULT_COLLECTOR_NAME;
            } else {
                _objectName = default_collectorName;
            } 
        }
//    }
    return _objectName;
}

- (void) setObjectName:(NSString *)objectName
{
    if (objectName != _objectName) {
        _objectName = objectName;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([self.objectType isEqualToString:@"Customer"])
        {
            [defaults setObject:objectName forKey:CUSTOMER_DEFAULT_NAME];
        } else if ([self.objectType isEqualToString:@"Collector"]) {
            [defaults setObject:objectName forKey:COLLECTOR_DEFAULT_NAME];
        }
        [defaults synchronize];
    }    
}

- (CAGradientLayer *)backgroundLayer
{
    //Create the gradient layer
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    gradientLayer.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                                                     (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                                                     (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                                                     (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                                                     (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                                                     nil];
    
    gradientLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f],
                                                        [NSNumber numberWithFloat:0.5f],
                                                        [NSNumber numberWithFloat:0.5f],
                                                        [NSNumber numberWithFloat:0.8f],
                                                        [NSNumber numberWithFloat:1.0f],
                               nil];
    return gradientLayer;
}   

- (void)setCustomerTableView:(UITableView *)customerTableView
{
    _customerTableView = customerTableView;
    self.customerTableView.backgroundView = nil;
    self.customerTableView.backgroundColor = [UIColor blackColor];
    self.customerTableView.delegate = self;
    self.customerTableView.dataSource = self;
}

- (void)setToolBar:(UIToolbar *)toolBar
{
    _toolBar = toolBar;
    //self.toolBar.barStyle = UIBarStyleBlackTranslucent;
    self.toolBar.backgroundColor = [UIColor lightGrayColor];

    /* commented out, no customer brand to avoid confusion with Oracle brand.  
    NSURL *imageURL = [NSURL URLWithString:@"http://www.toms-blog.com/images/Medium/microsoft-icon-new.jpg"];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
    UIImage *newImage = [self scaleImage:image toSize:CGSizeMake(36, 36)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.toolBar.frame.size.width, self.toolBar.frame.size.height)];
    imageView.contentMode = UIViewContentModeLeft;
    imageView.image = newImage;
    
    [self.toolBar insertSubview:imageView atIndex:0];
    [self.toolBar bringSubviewToFront:imageView];
     */

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.splitViewController.delegate = self;
    self.navigationController.toolbarHidden = NO;
    if ([self.objectType isEqualToString:@"Collector"]) {
        self.collectorImageView.hidden = NO;
    } else {
        self.collectorImageView.hidden = YES;
    }
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [self setCustomerTableView:nil];
    [self setCustomerHeaderView:nil];
    [self setDetailButton:nil];
    [self setToolBar:nil];
    [self setCustomerButton:nil];
    [self setCollectorImageView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [self.customerTableView reloadData];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"CollectorsPopoverIdentifier"])
    {
        UIStoryboardPopoverSegue *popSegue = (UIStoryboardPopoverSegue *)segue;
        popSegue.popoverController.delegate = self;
        self.popoverVC = popSegue.popoverController;
        CollectorsListTableViewController *collectorVC = (CollectorsListTableViewController *)segue.destinationViewController;
        collectorVC.popoverDeleage = self;
    } else if ([segue.identifier isEqualToString:@"CustomersPopoverIdentifier"])
    {
        UIStoryboardPopoverSegue *popSegue = (UIStoryboardPopoverSegue *)segue;
        popSegue.popoverController.delegate = self;
        self.topPopoverVC = popSegue.popoverController;
        TopDelinquentCustomersViewController *collectorVC = (TopDelinquentCustomersViewController *)segue.destinationViewController;
        collectorVC.topPopoverDeleage = self;
        collectorVC.objectType = self.objectType;
    }
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [self.customerTableView reloadData];
}  

- (id <SplitViewBarButtonItemPresenter>) splitViewBarButtonItemPresenter
{
    id detailVC = [self.splitViewController.viewControllers lastObject];
    if (![detailVC conformsToProtocol:@protocol(SplitViewBarButtonItemPresenter)]) {
        detailVC = nil;
    }
    return detailVC;
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

/*
- (BOOL) splitViewController:(UISplitViewController *)svc
    shouldHideViewController:(UIViewController *)vc
               inOrientation:(UIInterfaceOrientation)orientation
{
    return NO;
}
*/

- (BOOL) splitViewController:(UISplitViewController *)svc
    shouldHideViewController:(UIViewController *)vc
               inOrientation:(UIInterfaceOrientation)orientation
{
    return [self splitViewBarButtonItemPresenter] ? UIInterfaceOrientationIsPortrait(orientation) : NO;
}

- (void) splitViewController:(UISplitViewController *)svc
      willHideViewController:(UIViewController *)aViewController
           withBarButtonItem:(UIBarButtonItem *)barButtonItem
        forPopoverController:(UIPopoverController *)pc
{
    barButtonItem.title = self.title;
    [self splitViewBarButtonItemPresenter].splitViewBarButtonItem = barButtonItem;
}

- (void) splitViewController:(UISplitViewController *)svc
      willShowViewController:(UIViewController *)aViewController
   invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    [self splitViewBarButtonItemPresenter].splitViewBarButtonItem = nil;
}

- (void)dismissAtTap
{
    [self.customerTableView reloadData];
    NSLog(@"Object name is %@", self.objectName);
    
    [self.customerButton setTitle:self.objectName];
    [self.popoverVC dismissPopoverAnimated:YES];
    [self.topPopoverVC dismissPopoverAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;
    if ([self.objectType isEqualToString:@"Customer"])
    {
        numberOfRows = [customerMetricList count] ;
    } else if ([self.objectType isEqualToString:@"Collector"]) 
    {
        numberOfRows = [collectorMetricList count];
    }
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MetricCellIdentifier = @"Metric Cell";
//    static NSString *CollectorCellIdentifier = @"Collector Cell";
    
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:MetricCellIdentifier];
        
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MetricCellIdentifier];
    }

    cell.textLabel.bounds = CGRectMake(0, 0, 160, 60);
    cell.textLabel.frame = CGRectMake(0, 0, 160, 60);
    cell.detailTextLabel.bounds = CGRectMake(200, 0, 80, 60);
    cell.detailTextLabel.frame = CGRectMake(200, 0, 80, 60);
    if ([self.objectType isEqualToString:@"Customer"])
    {
        cell.textLabel.text = [customerMetricList objectAtIndex: indexPath.row];
        cell.detailTextLabel.text = [customerMetricValueList objectAtIndex: indexPath.row];
        if ([customerMetricsWithAnalyticsList containsObject:cell.textLabel.text]) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

    } else if ([self.objectType isEqualToString:@"Collector"]) {
        cell.textLabel.text = [collectorMetricList objectAtIndex: indexPath.row];
        cell.detailTextLabel.text = [collectorMetricValueList objectAtIndex: indexPath.row];        
        if ([collectorMetricsWithAnalyticsList containsObject:cell.textLabel.text]) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
        
    //tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    cell.backgroundColor = [UIColor darkGrayColor];
    cell.textLabel.textColor = [UIColor lightGrayColor];
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 2;
    [cell.textLabel sizeToFit];
    
    if ([cell.textLabel.text isEqualToString:@"Net Balance"] || [cell.textLabel.text isEqualToString:@"Amount Overdue"]) {
        UILabel *uomLabel = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width - 50, 10, 30, 30)];
        uomLabel.text = @"USD";
        uomLabel.font = [UIFont systemFontOfSize:7];
        uomLabel.backgroundColor = [UIColor darkGrayColor];
        uomLabel.textColor = [UIColor whiteColor];
        [cell addSubview:uomLabel];
    }

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return @"Metrics";
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 8, tableView.bounds.size.width -16, 16)];
    headerLabel.text = @"Metrics";
    headerLabel.textColor = [[UIColor alloc] initWithRed:85 green:85 blue:85 alpha:0.5];
    headerLabel.backgroundColor = [UIColor blackColor];
    headerLabel.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:headerLabel];
    headerView.backgroundColor = [UIColor blackColor];
    return headerView;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    if (indexPath.section == 0) {

        if ([self.objectType isEqualToString:@"Customer"]) {
            if (indexPath.row == 0 || indexPath.row == 1) {
                NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, self.balanceDetailViewController, nil];
                self.splitViewController.viewControllers = viewControllers;
            } 
            else if(indexPath.row == 2) {
                NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, self.dsoViewController, nil];
                self.splitViewController.viewControllers = viewControllers;
                
            }         
            
            else {
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
                
              
                if (indexPath.row == 2) {
                    GraphViewController *detailViewController = [storyBoard instantiateViewControllerWithIdentifier:@"graphViewController"];
                    
                    detailViewController.objectType = self.objectType;                 
                    detailViewController.graphName = @"DSO"; NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, detailViewController, nil];
                    self.splitViewController.viewControllers = viewControllers;
                    
                } else if (indexPath.row == 6) {
                  
                    NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, self.percentCurrentViewController, nil];
                    self.splitViewController.viewControllers = viewControllers;
  
                    
                } 
                               
                //             [[self.splitViewController.viewControllers lastObject] presentViewController:detailViewController animated:YES completion:^(void){}];
                //          NSArray *viewControllers = [[NSArray alloc]initWithObjects:[self.splitViewController.viewControllers objectAtIndex:0], detailViewController, nil];
                //        self.splitViewController.viewControllers = viewControllers;
                //        GraphViewController * detailViewController = (GraphViewController *)[self.splitViewController.viewControllers lastObject];
                //        [detailViewController performSegueWithIdentifier:@"Home" sender:detailViewController];
                
            }
        } else if ([self.objectType isEqualToString:@"Collector"]) {
            if (indexPath.row == 0) {
                NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, self.CEIViewController, nil];
                self.splitViewController.viewControllers = viewControllers;
                
            } else if (indexPath.row == 4 || indexPath.row ==5 || indexPath.row == 2) {
                
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
                NSArray *viewControllers;
                
                if (indexPath.row == 4 || indexPath.row == 5) {
                    //UIViewController *detailViewController = [storyBoard instantiateViewControllerWithIdentifier:@"BalanceDetailViewController"];
                    viewControllers = [[NSArray alloc]initWithObjects:self, self.balanceDetailViewController, nil];
                } else {
                    AssignedCustomersViewController *detailViewController = [storyBoard instantiateViewControllerWithIdentifier:@"AssignedCustomersVC"];
                    detailViewController.collectorName = self.objectName;
                    /*
                    TopDelinquentCustomersViewController *detailViewController = (TopDelinquentCustomersViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"TopDelinquentCustomersViewController"];
                    detailViewController.objectType = @"Customer";
                     */
                     viewControllers = [[NSArray alloc]initWithObjects:self, detailViewController, nil];                    
                }
                
                self.splitViewController.viewControllers = viewControllers;                
            } else if (indexPath.row == 1) {
                UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];
                GraphViewController *detailViewController = [storyBoard instantiateViewControllerWithIdentifier:@"graphViewController"];
                detailViewController.objectType = self.objectType;
                detailViewController.graphName = @"sunburst_delinquency";
                NSArray *viewControllers = [[NSArray alloc]initWithObjects:self, detailViewController, nil];
                self.splitViewController.viewControllers = viewControllers;                
            }
        }
    }
}

@end
